package profiterole.android;

import java.io.File;

import profiterole.api.MapReduce;
import profiterole.api.OnUpdateStatusCallback;
import profiterole.api.Waffle;
import profiterole.mapreduce.Splitter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.profiterole.android.R;

public class SearchScreen extends Activity {

	ProgressThread progThread;
	Button applyButton;
	Button dictionaryButton;
	TextView resultText;
	Waffle<?> mapReduceDB = null;

	public static final String WORDS_TO_OCCURENCES_MAP = "WORDS_TO_OCCURENCES_MAP";
	public static final String STATUS_TEXT = "STATUS_TEXT";
	public static final String NO_FILE_ERROR = "NO_FILE_ERROR";
	public static final String SHELL_TEXT = "SHELL_TEXT";
	
	public boolean flagProtectButtonClick = true;

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.
	final Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			String text = msg.getData().getString(SHELL_TEXT);

			if (text != null) {
				resultText.setText(text);
			}
			String status = msg.getData().getString(STATUS_TEXT);

			if (status != null) {
				resultText.setText(status);
			}
			
			String error = msg.getData().getString(NO_FILE_ERROR);
			
			if (error != null) {
				resultText.setText(error);
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_screen);

		resultText = (TextView) findViewById(R.id.resultTextView);
		resultText.setMovementMethod(new ScrollingMovementMethod());

		applyButton = (Button) findViewById(R.id.applyButton);
		applyButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// check if map reduce was run and take text from inputs
				// TODO don't do null comparison check for isEmpty
				if(flagProtectButtonClick && mapReduceDB == null) {	
					progThread = new ProgressThread(handler);
					progThread.start();
					resultText.setText("");			
				}
				// TODO here add search word from edit text
				resultText.setText("Here add on for word count");
			}
		});

		dictionaryButton = (Button) findViewById(R.id.showResultButton);
		dictionaryButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(SearchScreen.this, DictionaryScreen.class);
				Bundle b = new Bundle();

				// TODO null comparison
				if(mapReduceDB != null)
					b.putString(WORDS_TO_OCCURENCES_MAP, mapReduceDB.getSortedUnModifiableList().toString());
				else
					b.putString(WORDS_TO_OCCURENCES_MAP, "Processing");
				i.putExtras(b); //Put your id to your next Intent
				startActivity(i);
			}
		});
	}

	// Also provide a setState(state) method to stop the thread gracefully.
	private class ProgressThread extends Thread {

		Handler mHandler;

		ProgressThread(Handler h) {
			mHandler = h;
		}

		@Override
		public void run() {

			// splits the file
			File folder = new File(Environment.getExternalStorageDirectory()
					+ "/Profiterole" + "/pg1661.txt");
			
			if(!folder.exists()) {
				Message msg = mHandler.obtainMessage();
				Bundle b = new Bundle();
				b.putString(NO_FILE_ERROR, "The folder doesn't exist");
				msg.setData(b);
				mHandler.sendMessage(msg);
				return;
			}

			// block button
			flagProtectButtonClick = false;
			File destFolder = new File(
					Environment.getExternalStorageDirectory() + "/Profiterole"
							+ "/MapJobs/");
			destFolder.mkdir();
			Splitter.splitFile(folder, destFolder, 10000);

			OnUpdateStatusCallback listener = new OnUpdateStatusCallback() {

				@Override
				public void onMediumTwo(String info) {
					sendMessage(info);
				}

				@Override
				public void onMediumOne(String info) {
					sendMessage(info);	
				}

				@Override
				public void onInit(String info) {					
					sendMessage(info);
				}

				@Override
				public void onFinish(String info) {
					sendMessage(info);
					applyButton.setClickable(true);
				}

				private void sendMessage(String s) {
					Message msg = mHandler.obtainMessage();
					Bundle b = new Bundle();
					b.putString(STATUS_TEXT, s);
					msg.setData(b);
					mHandler.sendMessage(msg);
				}
			};
			
			mapReduceDB = MapReduce.perform(destFolder,listener, null);
			
			flagProtectButtonClick = true;
			
			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString(SHELL_TEXT, "Result dictionary " + mapReduceDB.getSortedUnModifiableList().size()
					+ " entries");
			msg.setData(b);
			mHandler.sendMessage(msg);

		}
	}
}